import json

import requests
from faker import Faker
import hashlib
import random


# 4.航空公司有一个查询机票的接口:GET http://api.airplane.com/check?start=SZ&end=BJ&time=1，
# start为始发地点end为到达地点，time为航班的时间，共有time=1(6-10点)、time=2(13-17点)、ime=3(19-23点)三个时间段
# 返回结果为ison字符串:“"available":1."price”:3000)，available值1表示在这个时间段有该航段的航班，0表示没有,
# price的值表示该时间段该航段的机票价格，接口可查的起止城市为[BJ,TJ,'SH,NJ,XA,WH,ZZ,CS,XM,'GZSZ]，
# 每个航班的飞行时间均在单个时间段以内，且转机时间必须在不同的时间段，不考虑跨天的情况。
# 请编写一个脚本查询出从SZ到BJ的最便宜乘机方案。

def send_get(session, data):
    response = session.get("http://api.airplane.com/check", params=data)
    response.encoding = "utf-8"
    txt = response.text
    result = json.loads(txt)
    return result


session = requests.session()
data1 = [{"start": "SZ", "end": "BJ", "time": 1}, {"start": "SZ", "end": "BJ", "time": 2},
         {"start": "SZ", "end": "BJ", "time": 3}]
data2 = ["TJ", "SH", "NJ", "XA", "WH", "ZZ", "CS", "XM", "GZ"]
data3 = ["TJ", "SH", "NJ", "XA", "WH", "ZZ", "CS", "XM", "GZ", "SZ"]
min1 = 0
minurl1 = ""
min2 = 0
minurl2 = ""
min3 = 0
minurl3 = ""
# 不转机
for i in range(1, 4):
    data = data1[i]
    result = send_get(session, data)
    if result["available"] == 1:
        if min1 < result["price"]:
            min1 = result["price"]
            minurl = "{}>{}".format(data["start"], data["end"])
# 转机1次
for i in range(1, 4):
    for data in data2:
        data = {"start": "SZ", "end": data, "time": i}
        result1 = send_get(session, data)
        if result1["available"] == 0:
            continue
        for j in range(1, 4):  # 下一站
            if i >= j:
                continue
            data = {"start": data["end"], "end": "BJ", "time": j}
            result2 = send_get(session, data)
            if result2["available"] == 0:
                continue
            if min2 == 0 or min2 > result1["price"] + result2["price"]:
                min2 = result1["price"] + result2["price"]
                minurl2 = "SZ>{}>BJ".format(data2[j])
# 转机2次
for age in data2:
    data = {"start": "SZ", "end": age, "time": 1}
    result1 = send_get(session, data)
    if result1["available"] == 0:
        continue
    data4 = [a for a in data2 if a != age]
    for age1 in data4:
        data = {"start": age, "end": age1, "time": 2}
        result2 = send_get(session, data)
        if result2["available"] == 0:
            continue
        data={"start": age1, "end": "BJ", "time": 3}
        result3 = send_get(session, data)
        if result3["available"] == 0:
            continue
        if min3 == 0 or min3 > result1["price"] + result2["price"] + result3["price"]:
            min3 = result1["price"] + result2["price"] + result3["price"]
            minurl3 = "SZ>{}>{}>BJ".format(age, age1)

d=[{"url":minurl,"price":min1},{"url":minurl2,"price":min2},{"url":minurl3,"price":min3}]
min=0
minurl=""
for i in d:
    if i["price"] != 0:
        if min == 0 or min > i["price"]:
            min = i["price"]
            minurl = i["url"]
print(minurl,min)




